<template>
  <div class="login-page">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="decoration-circle circle-1"></div>
      <div class="decoration-circle circle-2"></div>
      <div class="decoration-circle circle-3"></div>
    </div>

    <!-- 主要内容区域 -->
    <div class="login-container">
      <!-- 登录卡片 -->
      <el-card class="login-card" shadow="always">
        <!-- 头部标题 -->
        <div class="login-header">
          <h2 class="login-title">欢迎登录</h2>
          <p class="login-subtitle">请输入您的账号信息</p>
        </div>

        <!-- 登录表单 -->
        <el-form
          ref="loginFormRef"
          :model="loginData"
          :rules="loginData.loginRules"
          class="login-form"
          size="large"
        >
          <!-- 学号输入 -->
          <el-form-item prop="stuNum">
            <el-input
              v-model="loginData.stuNum"
              placeholder="请输入学号"
              autofocus
              autocomplete="username"
              clearable
            >
              <template #prefix>
                <el-icon class="input-icon">
                  <User />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 密码输入 -->
          <el-form-item prop="password">
            <el-input
              v-model="loginData.password"
              type="password"
              placeholder="请输入密码"
              show-password
              clearable
              @input="setPs"
            >
              <template #prefix>
                <el-icon class="input-icon">
                  <Lock />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 验证码输入 -->
          <el-form-item prop="render">
            <div class="captcha-container">
              <el-input
                v-model="loginData.render"
                placeholder="验证码"
                maxlength="4"
                class="captcha-input"
                @keyup.enter="submitFormLogin(loginFormRef)"
              >
                <template #prefix>
                  <el-icon class="input-icon">
                    <Key />
                  </el-icon>
                </template>
              </el-input>
              <div class="captcha-image-wrapper">
                <img
                  ref="Render"
                  class="captcha-image"
                  title="点击更换验证码"
                  @click="changRender()"
                  alt="验证码"
                />
              </div>
            </div>
          </el-form-item>

          <!-- 记住密码 -->
          <el-form-item>
            <div class="remember-container">
              <el-checkbox
                v-model="loginData.rememberMe"
                @change="handleRememberChange"
                class="remember-checkbox"
              >
                记住密码
              </el-checkbox>
              <el-button
                type="text"
                class="forgot-password"
                @click="handleForgotPassword"
              >
                忘记密码？
              </el-button>
            </div>
          </el-form-item>

          <!-- 登录按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              class="login-button"
              :loading="loginIng"
              @click="submitFormLogin(loginFormRef)"
              size="large"
            >
              <span v-if="!loginIng">登录</span>
              <span v-else>登录中...</span>
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 注册链接 -->
        <div class="register-link">
          <span class="register-text">还没有账号？</span>
          <el-button type="text" class="register-btn" @click="goToRegister">
            立即注册
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import router from '../../router'
import { Bounce, TweenMax } from 'gsap'
import { ElMessage } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { Key, Lock, User } from '@element-plus/icons-vue'
import md5 from 'js-md5'
import auth from '../../utils/auth'
import Cookies from 'js-cookie'
import { useStore } from '@/store'
import { login } from '@/api/login'

const userStore = useStore()
const loginIng = ref(false)
const loginFormRef = ref(null)
const Render = ref(null)
const loginData = reactive({
  stuNum: Cookies.get('yourStuNum') || '',
  password: '',
  render: '',
  rememberMe: false,
  loginRules: {
    stuNum: [{ validator: validatorNum, trigger: 'blur' }],
    password: [{ validator: validatorPassword, trigger: 'blur' }],
    render: [{ validator: validatorRender, trigger: 'blur' }],
  },
})

// 初始化时检查是否有保存的密码
if (Cookies.get('yourPassword') && Cookies.get('yourStuNum')) {
  loginData.password = Cookies.get('yourPassword')
  loginData.rememberMe = true
}

onMounted(() => {
  TweenMax.staggerFrom(
    '.login-form .el-form-item',
    1,
    {
      opacity: 0,
      y: -50,
      duration: 1.5,
      ease: Bounce.easeOut,
    },
    0.3
  )
  // 初始化验证码
  changRender()
})
const setPs = () => {
  // 当用户修改密码时，清除记住的密码
  if (loginData.rememberMe) {
    Cookies.remove('yourPassword')
    loginData.rememberMe = false
  }
}
const submitFormLogin = formEl => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      loginIng.value = true
      login(
        {
          id: loginData.stuNum,
          password: md5(md5(loginData.password)),
        },
        loginData.render
      )
        .then(res => {
          loginIng.value = false

          if (res.success) {
            // 登录成功处理
            auth.setToken(res.token)

            // 处理记住密码功能
            if (loginData.rememberMe) {
              Cookies.set('yourPassword', loginData.password, { expires: 7 })
              Cookies.set('yourStuNum', loginData.stuNum, { expires: 7 })
            } else {
              Cookies.remove('yourPassword')
              Cookies.set('yourStuNum', loginData.stuNum, { expires: 1 })
            }

            // 更新用户状态
            userStore.loginSet(auth.getToken(), loginData.stuNum, res.name)

            // 延迟跳转，让用户看到成功消息
            setTimeout(() => {
              router.push({ path: '/user/article' })
            }, 1000)
          } else {
            // 登录失败处理
            ElMessage({
              type: 'error',
              message: res.message || '登录失败，请检查账号密码',
              duration: 3000,
            })
            changRender()
            loginData.render = ''
          }
        })
        .catch(error => {
          loginIng.value = false
          console.error('登录请求失败:', error)
          ElMessage({
            type: 'error',
            message: '网络错误，请稍后重试',
            duration: 3000,
          })
          changRender()
          loginData.render = ''
        })
    } else {
      ElMessage({
        type: 'error',
        message: '请完善信息！',
        duration: 2000,
      })
      return false
    }
  })
}

function validatorRender(rule, value, callback) {
  if (value && value.length === 4) {
    callback()
  } else {
    callback(new Error('请输入4位验证码'))
  }
}

function validatorPassword(rule, value, callback) {
  if (!value) {
    callback(new Error('请输入密码'))
    return
  }

  // 如果是记住的密码，直接通过验证
  if (loginData.rememberMe && Cookies.get('yourPassword')) {
    callback()
    return
  }

  const patt = /(?=.*\d)(?=.*[a-zA-Z])^.{6,20}$/
  if (patt.test(value)) {
    callback()
  } else {
    callback(new Error('密码需要在6-20位之间并包含字母和数字'))
  }
}

function validatorNum(rule, value, callback) {
  if (!value) {
    callback(new Error('请输入学号'))
    return
  }

  const treg = /^[0-9]\d*$/
  if (treg.test(value) && (value.length === 12 || value.length === 7)) {
    callback()
  } else {
    callback(new Error('请输入正确的学号（7位或12位数字）'))
  }
}

function changRender() {
  if (Render.value) {
    // 添加时间戳防止缓存
    Render.value.src = `/api/render?t=` + new Date().getTime()
  }
}

// 处理记住密码切换
const handleRememberChange = () => {
  if (!loginData.rememberMe) {
    // 取消记住密码时清除保存的密码
    Cookies.remove('yourPassword')
  }
}

function goToRegister() {
  router.push('/register')
}

// 处理忘记密码
const handleForgotPassword = () => {
  ElMessage({
    type: 'info',
    message: '请联系管理员重置密码',
    duration: 3000,
  })
}
</script>

<style scoped>
/* 页面整体样式 */
.login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  position: relative;
  overflow: hidden;
  font-family: 'Helvetica Neue', Arial, sans-serif;
}

/* 背景装饰元素 */
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 0;
}

.decoration-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.circle-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.circle-2 {
  width: 150px;
  height: 150px;
  top: 60%;
  right: 15%;
  animation-delay: 2s;
}

.circle-3 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
    opacity: 0.7;
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
    opacity: 0.3;
  }
}

/* 登录容器 */
.login-container {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 420px;
  padding: 20px;
}

/* 登录卡片 */
.login-card {
  border-radius: 20px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  animation: slideUp 0.8s ease-out;
}

.login-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 登录头部 */
.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-title {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 10px 0;
  background: linear-gradient(135deg, #409eff, #337ecc);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.login-subtitle {
  font-size: 16px;
  color: #7f8c8d;
  margin: 0;
  font-weight: 400;
}

/* 登录表单 */
.login-form {
  margin-bottom: 30px;
}

.login-form .el-form-item {
  margin-bottom: 25px;
}

.input-icon {
  color: #409eff;
  font-size: 18px;
}

/* 验证码容器 */
.captcha-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-input {
  flex: 1;
}

.captcha-image-wrapper {
  flex-shrink: 0;
}

.captcha-image {
  width: 100px;
  height: 42px;
  border-radius: 8px;
  cursor: pointer;
  border: 2px solid #e1e8ed;
  transition: all 0.3s ease;
  object-fit: cover;
  display: block;
}

.captcha-image:hover {
  border-color: #409eff;
  transform: scale(1.05);
}

/* 登录按钮 */
.login-button {
  width: 100%;
  height: 50px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 12px;
  background: linear-gradient(135deg, #409eff, #337ecc);
  border: none;
  transition: all 0.3s ease;
}

.login-button:hover {
  background: linear-gradient(135deg, #337ecc, #2b6cb0);
  transform: translateY(-2px);
  box-shadow: 0 10px 20px rgba(64, 158, 255, 0.3);
}

/* 注册链接 */
.register-link {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.register-text {
  color: #909399;
  font-size: 14px;
  margin-right: 8px;
}

.register-btn {
  color: #409eff;
  font-weight: 500;
  padding: 0;
  font-size: 14px;

  &:hover {
    color: #337ecc;
    text-decoration: underline;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    max-width: 90%;
    padding: 10px;
  }

  .login-card {
    padding: 30px 20px;
  }

  .login-title {
    font-size: 24px;
  }

  .captcha-container {
    flex-direction: column;
    gap: 15px;
  }

  .captcha-image {
    width: 120px;
    height: 45px;
  }
}

/* Element Plus 组件样式覆盖 */
:deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

:deep(.el-card__body) {
  padding: 0;
}

:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #409eff, #337ecc);
  color: white;
  padding: 20px 24px;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 20px 24px;
  background: #f8f9fa;
}

/* 动画效果 */
.v-enter-active,
.v-leave-active {
  transition: all 0.3s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
  transform: scale(0.9);
}
</style>
